<?php
/**
 * author:huhaiqin
 * time:2019-11-12
 * feature:公共函数
 */

/**
 * huhaiqin,2023.08.16
 * 树结构水平化
 */
function tree_to_list($tree,$result=[],$level = 0){
    for($i = 0; $i < count($tree); $i++){
        $tmp = $tree[$i];
        $children = $tmp['children'];
        unset($tmp['children']);
        $tmp['level'] = $level;
        $result[] = $tmp;
        if($children){
            $result = tree_to_list($children ,$result,$level+1);
        }
    }
    return $result;
}

/**
 * 日志记录，2022.03.24
 */
function _log($content=''){
    return D('Log')->_edit($_SESSION['loginUser']['id'],$content);
}

/**
 * 获取当前用户id
 */
function get_uid(){
    $user = session('loginUser');
    return $user['id'];
}

/**
 * 检测是否为管理员
 */
function is_admin(){
    $user = session('loginUser');
    return $user['role'] == 'admin' ? true : false;
}

/**
 * 获取当前登录用户信息，优先使用当前登录用户，如果没有，则检测一下uid参数
 */
function get_user($uid = 0){
    $user = session('loginUser');
    if(!$user && $uid != 0){
        $user = M('Users')->find($uid);
        unset($user['password']);
    }
    return $user;
}

/**
 * huhaiqin,2023.06.12
 * 获取文件夹下面的文件内容
 */
function get_dir_content($path){
    if(!is_dir($path)){
        return false;
    }
    //scandir方法
    $arr = array();
    $data = scandir($path);
    foreach ($data as $value){
        if($value != '.' && $value != '..'){
            $arr[] = $value;
        }
    }
    return $arr;
}

//验证手机格式
function check_phone($phone){
    $check = '/^(1(([3456789][0-9])|(47)))\d{8}$/';
    if (preg_match($check, $phone)) {
        return true;
    } else {
        return false;
    }
}

//验证邮箱格式
function check_email($email){
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return false;
    } else {
        return true;
    }
}

//将数组转化成转成成sql里面查询in的value值
function change_arr_to_sql_in_value($arr = [],$tostr = false){
    if(is_string($arr)){
        if($tostr){
            return '"'.$arr.'"'; //如果本身就是字符串，直接返回
        }else{
            return $arr;
        }
    }
    if($tostr){
        $tmp = [];
        foreach($arr as $k=>$v){
            $tmp[$k] = '"'.$v.'"';
        }
        return implode(',',$tmp);
    }else{
        return implode(',',$arr);
    }
}

/**
* 生成token
* token = md5(token_key+token_time) tokenTime的范围-0.5day < tokenTime < +0.5day
*/
function create_token($token_time = 0){
    if($token_time == 0){
        $token_time = time();
    }
    return md5(C('app.token_key').$token_time);
}
/**
 * 校验token 
 * token = md5(token_key+token_time) tokenTime的范围-0.5day < tokenTime < +0.5day
 */
function check_token($token='',$token_time=0){
    $validate = new \Think\Validate;
    $validate->rule([
        'token'  => 'require',
        'token_time' => 'require|number'
    ]);

    $data = [
        'token'  => $token,
        'token_time' => $token_time
    ];

    if (!$validate->check($data)) {
        return [-1,$validate->getError()];
    }

    $time = time();
    if($token_time > $time - 43200 && $token_time < $time + 43200){
        if(md5(C('app.token_key').$token_time) == $token){
            return [0,'success']; //校验成功
        }else{
            return [-1,'无效token'];
        }
    }else{
        return [-1,'token过期'];
    }
}

/**
 * 在接口里实现token校验
 */
function check_token_api($token='',$token_time=0){
    $check_token = check_token($token,$token_time);
    if($check_token[0] == 0){
        return true;
    }else{
        _apiReturn(0,$check_token[1]); //直接接口返回错误
    }
}

/**
 * 输出json，作为api接口的统一返回
 * param
 *   status: int //状态码
 *   info: string //状态信息
 *   data: mixed //数据
 *   url: string //跳转地址
 * return void
 */
function _apiReturn($status,$info,$data='',$url=''){
	// 返回JSON数据格式到客户端 包含状态信息
    header('Content-Type:application/json; charset=utf-8');
    header("Access-Control-Allow-Origin: *");  //跨域请求
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
    header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS');
    if($_REQUEST['token'] && $_REQUEST['token_time']){
        $check_token = check_token($_REQUEST['token'],$_REQUEST['token_time']);
        if($check_token[0] == 0){
            //如果token校验成功，方可跨域
            // header("Access-Control-Allow-Origin: *");  //跨域请求
        }else{
            //处理token校验失败的情况
            $status = 0;
            $info = $check_token[1];
            $data = '';
            $url = '';
        }
    }
	if(C('api_table')){
		$status = $status ? 0 : 1;
		exit(json_encode(['code'=>$status,'msg'=>$info,'count'=>(int)$data['page']['total'],'data'=>$data['data']],JSON_UNESCAPED_UNICODE));
	}else{
		exit(json_encode(ajax_data_tpl($status,$info,$data,$url),JSON_UNESCAPED_UNICODE));
	}
    return;
}

/**
 * 固定ajax数据返回格式，沿用thinkphp3.1版本的格式
 * @param unknown $status
 * @param unknown $info
 * @param unknown $data
 */
function ajax_data_tpl($status,$info,$data,$url){
	$result = array(
		'status' => $status,
		'info' => $info,
		'data' => $data,
		'url' => $url
	);
	return $result;
}

/**
 * 读取Html
 */
function readHtml($htmlpath=''){
	$file = $htmlpath.md5($_SERVER["REQUEST_URI"]).C('HTML_FILE_SUFFIX');

	if(is_file($file)){
		echo file_get_contents($file);
		die();
	}
}
/**
 * 静态化页面
 */
function buildHtml($htmlpath=''){
	if($_POST['hhq-post-info'] == 'end'){
		die();
	}

	$url = "http://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
	$ch = curl_init();
	$curlPost = array('hhq-post-info'=>'end');
	curl_setopt($ch, CURLOPT_URL, $url);  // 设置要抓取的页面地址
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);              // 抓取结果直接返回（如果为0，则直接输出内容到页面）
	curl_setopt($ch, CURLOPT_HEADER, 0);                      // 不需要页面的HTTP头
	curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
	$content = curl_exec($ch);
	curl_close($ch);

	$htmlpath = !empty($htmlpath)?$htmlpath:HTML_PATH;
	$htmlfile = md5($_SERVER["REQUEST_URI"]);
	$htmlfile =  $htmlpath.$htmlfile.C('HTML_FILE_SUFFIX');
	//创建文件夹目录
	$dir = dirname($htmlfile);
	if(!is_dir($dir)){
		mkdir($dir,0777,true);
	}
	file_put_contents($htmlfile,$content);
}

/**
 * 接口查询条件string转array
 * __表示两个条件参数的连接符
 * |= 表示参数的值
 * #= 表示参数值的关联关系
 */
function condition_to_array($condition_str){
	$tmparr = array();
	$tmp = explode('__',$condition_str);
	foreach($tmp as $t){
		$tt = explode('|_|',$t);
		if(count($tt)!= 2){
			return false;
		}else{
			$ttt = explode('*_*',$tt[1]);
			if(count($ttt) == 2){
				$tttt = array($ttt[0],$ttt[1]);
			}else{
				$tttt = $tt[1];
			}
			$tmparr[$tt[0]] = $tttt;
		}
	}
	return $tmparr;
}

/**
 * 将查询条件数组编译成字符串
 */
function condition_to_str($condition_array){
	$tmparr = array();
	foreach($condition_array as $key=>$val){
		$tmp = $val;
		if(is_array($val)){
			$tmp = implode('*_*',$val);
		}
		$tmparr[] = $key.'|_|'.$tmp;
	}
	return implode('__',$tmparr);
}

/**
 * 系统非常规MD5加密方法
 * @param $str
 * @param string $key
 * @return string
 * @author:wdx(wdx@ourstu.com)
 */
function think_md5($str, $key = 'ThinkUCenter')
{
    return '' === $str ? '' : md5(sha1($str) . $key);
}

/**
 * 系统加密方法
 * @param string $data 要加密的字符串
 * @param string $key 加密密钥
 * @param int $expire 过期时间 (单位:秒)
 * @return string
 */
function think_encrypt($data, $key, $expire = 0)
{
    $key = md5($key);
    $data = base64_encode($data);
    $x = 0;
    $len = strlen($data);
    $l = strlen($key);
    $char = '';
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }
    $str = sprintf('%010d', $expire ? $expire + time() : 0);
    for ($i = 0; $i < $len; $i++) {
        $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1))) % 256);
    }
    return str_replace('=', '', base64_encode($str));
}

/**
 * 系统解密方法
 * @param string $data 要解密的字符串 （必须是think_encrypt方法加密的字符串）
 * @param string $key 加密密钥
 * @return string
 */
function think_decrypt($data, $key)
{
    $key = md5($key);
    $x = 0;
    $data = base64_decode($data);
    $expire = substr($data, 0, 10);
    $data = substr($data, 10);
    if ($expire > 0 && $expire < time()) {
        return '';
    }
    $len = strlen($data);
    $l = strlen($key);
    $char = $str = '';
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }
    for ($i = 0; $i < $len; $i++) {
        if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))) {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        } else {
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return base64_decode($str);
}

/**
 * text函数用于过滤标签，输出没有html的干净的文本
 * @param string text 文本内容
 * @return string 处理后内容
 */
function text($text, $addslanshes = false)
{
    $text = nl2br($text);
    $text = real_strip_tags($text);
    if ($addslanshes)
        $text = addslashes($text);
    $text = trim($text);
    return $text;
}

/**
 * html函数用于过滤不安全的html标签，输出安全的html
 * @param string $text 待过滤的字符串
 * @param string $type 保留的标签格式
 * @return string 处理后内容
 */
function html($text, $type = 'html')
{
    // 无标签格式
    $text_tags = '';
    //只保留链接
    $link_tags = '<a>';
    //只保留图片
    $image_tags = '<img>';
    //只存在字体样式
    $font_tags = '<i><b><u><s><em><strong><font><big><small><sup><sub><bdo><h1><h2><h3><h4><h5><h6>';
    //标题摘要基本格式
    $base_tags = $font_tags . '<p><br><hr><a><img><map><area><pre><code><q><blockquote><acronym><cite><ins><del><center><strike>';
    //兼容Form格式
    $form_tags = $base_tags . '<form><input><textarea><button><select><optgroup><option><label><fieldset><legend>';
    //内容等允许HTML的格式
    $html_tags = $base_tags . '<ul><ol><li><dl><dd><dt><table><caption><td><th><tr><thead><tbody><tfoot><col><colgroup><div><span><object><embed><param>';
    //专题等全HTML格式
    $all_tags = $form_tags . $html_tags . '<!DOCTYPE><meta><html><head><title><body><base><basefont><script><noscript><applet><object><param><style><frame><frameset><noframes><iframe>';
    //过滤标签
    $text = real_strip_tags($text, ${$type . '_tags'});
    // 过滤攻击代码
    if ($type != 'all') {
        // 过滤危险的属性，如：过滤on事件lang js
        while (preg_match('/(<[^><]+)(ondblclick|onclick|onload|onerror|unload|onmouseover|onmouseup|onmouseout|onmousedown|onkeydown|onkeypress|onkeyup|onblur|onchange|onfocus|action|background[^-]|codebase|dynsrc|lowsrc)([^><]*)/i', $text, $mat)) {
            $text = str_ireplace($mat[0], $mat[1] . $mat[3], $text);
        }
        while (preg_match('/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i', $text, $mat)) {
            $text = str_ireplace($mat[0], $mat[1] . $mat[3], $text);
        }
    }
    return $text;
}

/**
 * 获取全球唯一标识
 * @return string
 */
function uuid()
{
    return sprintf(
        '%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0x0fff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000, mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
    );
}

/**
 * 将数组转化成树
 * @param $list
 * @param string $pk
 * @param string $pid
 * @param string $child
 * @param int $root
 * @return array
 * @author:wdx(wdx@ourstu.com)
 */
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0)
{
    // 创建Tree
    $tree = array();
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            if (empty($list[$key]['child'])) {
                $list[$key]['child'] = null;
            }
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];

                    if ($parent == null) {
                        $parent[$child][] = null;
                    } else {
                        $parent[$child][] =& $list[$key];
                    }
                }
            }
        }
    }
    return $tree;
}

/**
 * 将list_to_tree的树还原成列表
 * @param  array $tree 原来的树
 * @param  string $child 孩子节点的键
 * @param  string $order 排序显示的键，一般是主键 升序排列
 * @param  array $list 过渡用的中间数组，
 * @return array        返回排过序的列表数组
 * @author yangweijie <yangweijiester@gmail.com>
 */
function tree_to_list_other($tree, $child = '_child', $order = 'id', &$list = array())
{
    if (is_array($tree)) {
        $refer = array();
        foreach ($tree as $key => $value) {
            $reffer = $value;
            if (isset($reffer[$child])) {
                unset($reffer[$child]);
                tree_to_list_other($value[$child], $child, $order, $list);
            }
            $list[] = $reffer;
        }
        $list = list_sort_by($list, $order, $sortby = 'asc');
    }
    return $list;
}

/** 
 * 获取客户端浏览器类型及版本号
 * 
 * @param mixed $glue 传入分隔符的时候  返回字符串
 * @return mixed  默认返回array
 */
function get_client_browser($glue = null)
{
    $browser = [];
    
    $agent = request()->header('USER_AGENT');
    
    $regex = [
        'ie'      => '/(MSIE) (\d+\.\d)/',
        'chrome'  => '/(Chrome)\/(\d+\.\d+)/',
        'firefox' => '/(Firefox)\/(\d+\.\d+)/',
        'opera'   => '/(Opera)\/(\d+\.\d+)/',
        'safari'  => '/Version\/(\d+\.\d+\.\d) (Safari)/',
    ];
    
    foreach ($regex as $type => $reg) :
        preg_match($reg, $agent, $data);
        if (!empty($data) && is_array($data)) :
            $browser = $type === 'safari' ? array($data[2], $data[1]) : array($data[1], $data[2]);
            break;
        endif;
    endforeach;
    
    return empty($browser) ? false : (is_null($glue) ? $browser : implode($glue, $browser));
}

/** 
 * 获取客户端操作系统信息
 * 
 * @return string 
 */
function get_client_os()
{
    $agent = request()->header('USER_AGENT');
    
    $os = 'unkown';
    
    $regex = [
        [['/win/i', '/nt 6.0/i'], 'Windows Vista'],
        [['/win/i', '/nt 6.1/i'], 'Windows 7'],
        [['/win/i', '/nt 6.2/i'], 'Windows 8'],
        [['/win/i', '/nt 10.0/i'], 'Windows 10'],
        [['/win/i', '/nt 5.1/i'], 'Windows XP'],
        [['/win/i', '/nt 5/i'], 'Windows 2000'],
        [['/win/i', '/nt/i'], 'Windows NT'],
        [['/win/i', '/32/i'], 'Windows 32'],
        [['/linux/i'], 'Linux'],
        [['/unix/i'], 'Unix'],
        [['/sun/i', '/os/i'], 'SunOS'],
        [['/ibm/i', '/os/i'], 'IBM OS/2'],
        [['/Mac/i', '/PC/i'], 'Macintosh'],
        [['/PowerPC/i'], 'PowerPC'],
        [['/AIX/i'], 'AIX'],
        [['/HPUX/i'], 'HPUX'],
        [['/NetBSD/i'], 'NetBSD'],
        [['/BSD/i'], 'BSD'],
        [['/OSF1/i'], 'OSF1'],
        [['/IRIX/i'], 'IRIX'],
        [['/FreeBSD/i'], 'FreeBSD'],
        [['/teleport/i'], 'teleport'],
        [['/flashget/i'], 'flashget'],
        [['/webzip/i'], 'webzip'],
        [['/offline/i'], 'offline'],
    ];
    
    foreach ($regex as $key => $reg) :
        $pre = false;
        foreach ($reg[0] as $key => $val) :
            $pre = preg_match($val, $agent);
        endforeach;
        if ($pre) :
            $os = $reg[1];
            break;
        endif;
    endforeach;
    
    return $os;
}

/**
 * 格式化字节
 * 
 * @param integer $size 转换的数据
 * @param string $delimiter 转换后的分割符 默认没有分隔符
 * @return string 返回带单位的大小
 */
function get_byte($size, $delimiter = '')
{
    $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
    
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
        
    return round($size, 2) . $delimiter . $units[$i];
}

/**
 * 字符串截取
 * 
 * @param string $sourcestr 要截取的内容
 * @param integer $cutlength 指定长度
 * @return string 截取后的结果
 */
function cut_str($sourcestr, $cutlength)
{
    $returnstr = '';
    $i = 0;
    $n = 0;
    
    $str_length = strlen($sourcestr);
    while (($n < $cutlength) and ($i <= $str_length)) {
        $temp_str = substr($sourcestr, $i, 1);
        $ascnum = Ord($temp_str);
        if ($ascnum >= 224) { 
            $returnstr = $returnstr.substr($sourcestr, $i, 3);
            $i += 3;
            $n++; 
        } elseif ($ascnum >= 192) {
            $returnstr = $returnstr.substr($sourcestr, $i, 2); 
            $i += 2;
            $n++; 
        } elseif ($ascnum >= 65 && $ascnum <= 90) {
            $returnstr = $returnstr.substr($sourcestr, $i, 1);
            $i += 1;
            $n++;
        } else {
            $returnstr = $returnstr.substr($sourcestr, $i, 1);
            $i += 1;
            $n += 0.5; 
        }
    }
    if ($str_length > $cutlength) {
        $returnstr = $returnstr . "...";
    }

    return $returnstr;
}

/**
 * 补白操作，默认左侧补零
 * 
 * @param mixed $str 需要补白操作的字符或数字
 * @param integer $len 全局长度
 * @param string $pad 补白的字符，默认补0
 * @param integer $position 补白位置  默认左侧，，0=左侧，1=右侧，2=两边
 * @return string 补白后的字符串
 */
function fill_pad($str, $len, $pad = '0', $position = 0)
{
    $position = intval($position);
    
    if($position > 2) $position = 0;
    
    $pad_type = [0 => STR_PAD_LEFT, 1 => STR_PAD_RIGHT, 2 => STR_PAD_BOTH];
    
    return str_pad($str, $len, $pad, $pad_type[$position]);
}

/**
 * sprintf 补白操作，默认左侧补零
 * 
 * @param mixed $str 需要补白操作的字符串或数字
 * @param integer $len 全局长度
 * @param string $pad 补白的字符，默认补0
 * @param string $position 补白位置  默认左侧，，+=左侧，-=右侧
 * @return string 补白后的字符串
 */
function fill_pad_sprintf($str, $len, $pad = '0', $position = '+')
{
    $sprintf_str = '%' . $position . $pad . $len . 's';
    
    return sprintf($sprintf_str, $str);
}

/**
 * 去小数取整 --舍弃小数   示例：比如20.0003=20,20.9888=20
 * 
 * @param mixed $v 需要处理的数字
 * @return string 处理后的数据
 */
function get_integer_giveup($v)
{
    $str_v = bcadd(strval($v), 0, 10);
    
    return bcadd(explode('.', $str_v)[0], 0, 2);
}

/**
 * 去小数进位--如小数位   示例：20.00=20,20.98=21,20.00003=21
 * 
 * @param mixed $v 需要处理的数字
 * @return string 处理后的数据
 */
function get_integer_carry($v)
{
    $str_v = bcadd(strval($v), 0, 10);
    
    $str_v_arr = explode('.', $str_v);
    
    $return_str = intval($str_v_arr[1]) == 0 ?
                    bcadd(strval($str_v_arr[0]), 0, 2) :
                    bcadd($str_v_arr[0], 1, 2);
    
    return $return_str;
}

/**
 * 指定小数位的数字四舍五入 示例：3.124取2位小数点=3.12，3.125取2位小数点=3.13
 * 
 * @param mixed $v 需要处理的数字
 * @return string 处理后的数据
 */
function get_integer_round($v, $dot = 2)
{
    return bcadd(round($v, $dot), 0, 2);
}

/**
 * 不支持个位进位---》采用get_integer_carry即可
 * 支持十位，百位以上的取整计算
 * 示例：1800.00=1800.00,1803.00=1900.00,1800.003=1900
 * 
 * @param mixed $v 需要处理的数字
 * @param string $bit  指定进位数   即个位为1，十位为2，百位为3，以此类推，最多支持到万位
 * @param integer $dot 指定小数点位数  默认保留小数点2位
 * @return string 处理后的结果
 */
function get_integer_roundup($v, $bit, $dot = 2)
{
    $bit = strval($bit);
    
    $arr = ['2' => 10, '3' => 100, '4' => 1000, '5' => 10000];
    
    $str_v = bcadd(strval($v), 0, 10);
    
    $str_v_arr = explode('.', $str_v);
    
    $return_str = "0.00";
    
    $return_str = intval($str_v_arr[1]) > 0 ? (
        bcadd(bcsub($str_v_arr[0], substr($str_v_arr[0], intval(('-' . ($bit-1)))), 6), $arr[$bit], $dot)
    ) : (
        intval(substr($str_v_arr[0], intval(('-' . ($bit-1))))) > 0 ? (
            bcadd(bcsub($str_v_arr[0], substr($str_v_arr[0], intval(('-' . ($bit-1)))), 6), $arr[$bit], $dot)
        ) : (
            bcadd($str_v_arr[0], 0, $dot)
        )
    );
    
    return $return_str;
}

/**
 * 将字符串转换为数组
 * 
 * @param string $str 转换的字符串
 * @param integer $pad 是否去除空白，0=不去除，1=去除------ 默认不去除
 * @return array 返回的结果
 */
function str_to_array($str, $pad = 0)
{
    $str = intval($pad) != 0 ? str_replace(' ', '', $str) : $str;
    
    $strlen = mb_strlen($str);
    
    $arr = [];
    
    while ($strlen) :
        $arr[] = mb_substr($str, 0, 1, "utf8");
        $str = mb_substr($str, 1, $strlen, "utf8");
        $strlen = mb_strlen($str);
    endwhile;
    
    return $arr;
}

/**
 * 身份证号码及银行卡号隐藏中间
 * 
 * @param string $card 需要处理的卡号
 * @return string 返回处理的结果
 */
function hidden_card_str($card)
{
    $length = strlen($card);
    
    $calcLength = $length - 8;
    
    return substr_replace($card, str_repeat('*', $calcLength), 4, $calcLength);
}

/**
 * 生成指定位数的token
 * 
 * @param integer $len 生成的token长度 默认32位
 * @param bool $md5 是够MD5加密  默认加密
 * @return string 生成的token
 */
function create_token_key($len = 32, $md5 = true)
{
    $chars = [
        'Q', '@', '8', 'y', '%', '^', '5', 'Z', '(', 'G', '_', 'O', '`',
        'S', '-', 'N', '<', 'D', '{', '}', '[', ']', 'h', ';', 'W', '.',
        '/', '|', ':', '1', 'E', 'L', '4', '&', '6', '7', '#', '9', 'a',
        'A', 'b', 'B', '~', 'C', 'd', '>', 'e', '2', 'f', 'P', 'g', ')',
        '?', 'H', 'i', 'X', 'U', 'J', 'k', 'r', 'l', '3', 't', 'M', 'n',
        '=', 'o', '+', 'p', 'F', 'q', '!', 'K', 'R', 's', 'c', 'm', 'T',
        'v', 'j', 'u', 'V', 'w', ',', 'x', 'I', '$', 'Y', 'z', '*'
    ];
    
    $chars_len = count($chars) - 1;
    
    $token = '';
    
    for ($i = 0; $i < $len; $i++) {
        $token .= $chars[mt_rand(0, $chars_len)];
    }
    if ($md5) {
        $chunks = ceil(strlen($token) / 32);
        $md5token = '';
        for ($i = 1; $i <= $chunks; $i++) {
            $md5token .= md5(substr($token, $i * 32 - 32, 32));
        }
        $token = substr($md5token, 0, $len);
    }
    
    return $token;
}

/**
 * 生成固定位数的org
 * 
 * @return string 
 */
function create_orgcode()
{
    $chars = [
        'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D',
        'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M',
        '1', '2', '3', '4', '5', '6', '7', '8', '9'
    ];
    
    $chars_len = count($chars) - 1;
    
    $org = '';
    for ($i = 0; $i < 32; $i++) {
        $org .= $chars[mt_rand(0, $chars_len)];
    }
    
    return strtoupper($org.uniqid());
}

/** 
 * 人民币小写转大写 
 * 
 * @name	num2rmb
 * @param 	string 	$number 		数值 
 * @param 	string 	$int_unit 		币种单位，默认"元"，有的需求可能为"圆" 
 * @param 	bool 	$is_round 		是否对小数进行四舍五入 
 * @param 	bool 	$is_extra_zero 	是否对整数部分以0结尾，小数存在的数字附加0,比如1960.30， 有的系统要求输出"壹仟玖佰陆拾元零叁角"，实际上"壹仟玖佰陆拾元叁角"也是对的 
 * @return string 
 */ 
function num2rmb($number = 0, $int_unit = '', $is_round = false, $is_extra_zero = false, $rmb = false) 
{ 
    // 将数字切分成两段 
    $parts = explode('.', $number, 2); 
    $int = isset($parts[0]) ? strval($parts[0]) : '0'; 
    $dec = isset($parts[1]) ? strval($parts[1]) : ''; 
    
    // 如果小数点后多于2位，不四舍五入就直接截，否则就处理 
    $dec_len = strlen($dec); 
    if (isset($parts[1]) && $dec_len > 2) { 
        $dec = $is_round 
                ? substr(strrchr(strval(round(floatval("0.".$dec), 2)), '.'), 1) 
                : substr($parts[1], 0, 2); 
    } 
    
    // 当number为0.001时，小数点后的金额为0元 
    if(empty($int) && empty($dec)) { 
        return '零'; 
    } 
    
    // 定义 
    if ($rmb) {
        $chs = array('0','壹','贰','叁','肆','伍','陆','柒','捌','玖'); 
        $uni = array('','拾','佰','仟'); 
        $dec_uni = array('角', '分'); 
        $exp = array('', '万'); 
    } else {
        $chs = array('0','一','二','三','四','五','六','七','八','九'); 
        $uni = array('','十','百','千'); 
        $dec_uni = array('角', '分'); 
        $exp = array('', '万'); 
    }
    
    $res = ''; 
    
    // 整数部分从右向左找 
    for ($i = strlen($int) - 1, $k = 0; $i >= 0; $k++) { 
        $str = ''; 
        // 按照中文读写习惯，每4个字为一段进行转化，i一直在减 
        for ($j = 0; $j < 4 && $i >= 0; $j++, $i--) {
            // 非0的数字后面添加单位 
            $u = $int{$i} > 0 ? $uni[$j] : ''; 
            $str = $chs[$int{$i}] . $u . $str; 
        } 
        //echo $str."|".($k - 2)."<br>"; 
        // 去掉末尾的0 
        $str = rtrim($str, '0');
        // 替换多个连续的0 
        $str = preg_replace("/0+/", "零", $str);
        if (!isset($exp[$k])) {
            // 构建单位 
            $exp[$k] = $exp[$k - 2] . '亿';
        } 
        $u2 = $str != '' ? $exp[$k] : ''; 
        $res = $str . $u2 . $res; 
    } 
    
    // 如果小数部分处理完之后是00，需要处理下 
    $dec = rtrim($dec, '0'); 
    
    // 小数部分从左向右找 
    if (!empty($dec)) { 
        $res .= $int_unit; 
    
        // 是否要在整数部分以0结尾的数字后附加0，有的系统有这要求 
        if ($is_extra_zero) { 
            if (substr($int, -1) === '0') { 
                $res.= '零'; 
            } 
        } 
    
        for($i = 0, $cnt = strlen($dec); $i < $cnt; $i++) {
            // 非0的数字后面添加单位 
            $u = $dec{$i} > 0 ? $dec_uni[$i] : '';
            $res .= $chs[$dec{$i}] . $u; 
        }
        // 去掉末尾的0 
        $res = rtrim($res, '0');
        // 替换多个连续的0 
        $res = preg_replace("/0+/", "零", $res);
    } else { 
        if ($rmb) {
            $res .= $int_unit . '整'; 
        }
    } 
    return $res; 
}

/**
 * 通过身份证获取出生日期、性别、年龄
 * 
 * @param 	string 		$idcard 		身份证号码18位
 * @return 	array
 */
function get_info_by_idcard($idcard)
{
    $res = [];
    $bir = substr($idcard, 6, 8);
    $year = substr($bir, 0, 4);
    $month = substr($bir, 4, 2);
    $day = substr($bir, 6, 2);
    $res['birthday'] = $year . "-" . $month . "-" . $day;
    
    $sn = substr($idcard, 16, 1);
    $sex = ($sn % 2 == 1) ? '01' : '02';
    $res['gender'] = $sex;
    
    $date = strtotime(substr($idcard, 6, 8));
    $today = strtotime('today');
    $diff = floor(($today-$date)/86400/365);
    $age = strtotime(substr($idcard, 6, 8) . ' +' . $diff . 'years') > $today ? ($diff + 1) : $diff; 
    $res['age'] = $age;
    
    return $res;
}

/**
 * 生成默认订单号
 * 
 * @param 	string 		$companyID		单位ID 		
 * @return 	string
 */
function generate_order_number($companyID)
{
    $order_id_main = date('YmdHis') . rand(10000000, 99999999); 
    $order_id_len = strlen($order_id_main);
    $order_id_sum = 0; 
    for ($i = 0; $i < $order_id_len; $i++) {    
        $order_id_sum += (int)(substr($order_id_main, $i, 1));
    }
    
    $number = $companyID . $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);
    return $number;
}

/**
 * 文件类型分类处理
 * 
 * @param 	string 		$suffix		
 * @return 	string
 */
function get_file_type($suffix)
{
    $suffix = strtolower($suffix);
    switch ($suffix) {
        //图片
        case 'gif':
        case 'jpg':
        case 'jpeg':
        case 'bmp':
        case 'png':
        case 'swf':
        case 'pcx':
        case 'tiff':
        case 'tga':
        case 'exif':
        case 'fpx':
        case 'svg':
        case 'psd':
        case 'cdr':
            $res = '01';
            break;
        case 'xls':
        case 'xlsx':
        case 'xlsm':
        case 'xlt':
        case 'xltx':
        case 'xltm':
        case 'doc':
        case 'docx':
        case 'ppt':
        case 'pps':
        case 'pptx':
        case 'pdf':
        case 'md':
        case 'rar':
        case 'zip':
        case '7z':
        case 'gz':
        case 'bz':
        case 'ace':
        case 'uha':
        case 'uda':
        case 'zpaq':
        case 'txt':
            $res = '02';
            break;
        case 'wmv':
        case 'asf':
        case 'asx':
        case 'rm':
        case 'rmvb':
        case 'mpg':
        case 'mpeg':
        case 'mpe':
        case '3gp':
        case 'mov':
        case 'mp4':
        case 'm4v':
        case 'avi':
        case 'dat':
        case 'mkv':
        case 'flv':
        case 'vob':
            $res = '03';
            break;
        case 'mp3':
        case 'ogg':
        case 'ape':
        case 'cda':
        case 'au':
        case 'midi':
        case 'mac':
        case 'aac':
            $res = '04';
            break;
        default:
            $res = '05';
            break;
    }

    return $res;
}

/**
 * huhaiqin,2023.05.30
 * 邮件发送函数
 * 2023.05.30 增加了参数 $from_name 与 $default_to_name
 */
function sendMail($to, $title, $content,$from_name = '',$default_to_name = '') {

    $from_name = $from_name != '' ? $from_name : C('MAIL_FROMNAME');
    $default_to_name = $default_to_name != '' ? $default_to_name : '尊敬的客户';
	Vendor('PHPMailer.PHPMailerAutoload');
	$mail = new PHPMailer(); //实例化
    $mail->IsSMTP(); // 启用SMTP
    // $mail->SMTPDebug = 2; 
    if(C('MAIL_IS_SSL')){
        $mail->SMTPSecure = 'ssl';
        $mail->Port = 465; // ssl端口用465
    }else{
        $mail->Port = 25;//非ssl端口用这个
    }
	$mail->Host=C('MAIL_HOST'); //smtp服务器的名称（这里以QQ邮箱为例）
	$mail->SMTPAuth = C('MAIL_SMTPAUTH'); //启用smtp认证
	$mail->Username = C('MAIL_USERNAME'); //你的邮箱名
	$mail->Password = C('MAIL_PASSWORD') ; //邮箱密码
	$mail->From = C('MAIL_FROM'); //发件人地址（也就是你的邮箱地址）
	$mail->FromName = $from_name; //发件人姓名
	$mail->AddAddress($to,$default_to_name);
	$mail->WordWrap = 50; //设置每行字符长度
	$mail->IsHTML(C('MAIL_ISHTML')); // 是否HTML格式邮件
	$mail->CharSet=C('MAIL_CHARSET'); //设置邮件编码
	$mail->Subject =$title; //邮件主题
	$mail->Body = $content; //邮件内容
	$mail->AltBody = ""; //邮件正文不支持HTML的备用显示
	return($mail->Send());
}

/**
 * 执行自身api
 * @param url $api
 * return array格式的返回数据
 */
function do_self_api($api){
	$home = C('home_url');
	return json_decode(file_get_contents($home.$api),true);
}

/**
 * post方式执行自身api
 * @param unknown $api
 * @param unknown $params
 */

function do_self_api_post($api,$params){
	$home = C('home_url');
	$url = $home.$api;
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
	$output = curl_exec($ch);
	curl_close($ch);
	return json_decode($output,true); //返回json数据
}

/*
 * 获取随机字符串
 */
function get_rand_char($length){
	$str = null;
	$strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
	$max = strlen($strPol)-1;

	for($i=0;$i<$length;$i++){
		$str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
	}
	return $str;
}

/*
 * 获取随机字符串
 */
function get_rand_num($length){
	$str = null;
	$strPol = "0123456789";
	$max = strlen($strPol)-1;

	for($i=0;$i<$length;$i++){
		$str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
	}
	return $str;
}

/**
 * @param $data 传入json对象获取第一个元素属性名
 * @return int|string
 * description
 */
function getFirstElementKey($data){
    $firstObj = '';
    foreach ($data as $k=>$v){
        return $firstObj = $k;
    }
}
function getFirstElementValue($data){
    $firstObj = '';
    foreach ($data as $k=>$v){
        return $firstObj = $v;
    }
}
/**
 * @param $data json对象
 * @param $childrenKey json二级元素键名
 * @return mixed
 * description  返回二级对象value
 */
function getChildenElementValue($data,$childrenKey){
    $firstObjValue = null;
    foreach ($data as $k=>$v){
        $firstObjValue = $v;
    }
    return $firstObjValue[$childrenKey];
}
function useToEditPageGetzujianName($name){
    if ($name == 'carouselTpl') return '图片轮播';
    if ($name == 'imgGroupTpl') return '单图组';
    if ($name == 'imgsGroupTpl') return '图片橱窗';
    if ($name == 'navTpl') return '导航组';
    if ($name == 'videoTpl') return '视频组';
    if ($name == 'articleTpl') return '文章组';
    if ($name == 'textEditTpl') return '富文本';
}

function deldir($dir) {
    $dh = opendir($dir);
    //循环删除文件夹下所有的缓存文件
    while ($file = readdir($dh)) {
        if($file != "." && $file!="..") {
            $fullpath = $dir."/".$file;
            if(!is_dir($fullpath)) {
                unlink($fullpath);
            } else {
                deldir($fullpath);
            }
        }
    }
    closedir($dh);
    //删除当前文件夹：
    if(rmdir($dir)) {
        return true;
    } else {
        return false;
    }
}
class Utf8ToPy {
    /**
     * 拼音字符转换图
     * @var array
     */
    private static $_aMaps = array(
        'a'=>-20319,'ai'=>-20317,'an'=>-20304,'ang'=>-20295,'ao'=>-20292,
        'ba'=>-20283,'bai'=>-20265,'ban'=>-20257,'bang'=>-20242,'bao'=>-20230,'bei'=>-20051,'ben'=>-20036,'beng'=>-20032,'bi'=>-20026,'bian'=>-20002,'biao'=>-19990,'bie'=>-19986,'bin'=>-19982,'bing'=>-19976,'bo'=>-19805,'bu'=>-19784,
        'ca'=>-19775,'cai'=>-19774,'can'=>-19763,'cang'=>-19756,'cao'=>-19751,'ce'=>-19746,'ceng'=>-19741,'cha'=>-19739,'chai'=>-19728,'chan'=>-19725,'chang'=>-19715,'chao'=>-19540,'che'=>-19531,'chen'=>-19525,'cheng'=>-19515,'chi'=>-19500,'chong'=>-19484,'chou'=>-19479,'chu'=>-19467,'chuai'=>-19289,'chuan'=>-19288,'chuang'=>-19281,'chui'=>-19275,'chun'=>-19270,'chuo'=>-19263,'ci'=>-19261,'cong'=>-19249,'cou'=>-19243,'cu'=>-19242,'cuan'=>-19238,'cui'=>-19235,'cun'=>-19227,'cuo'=>-19224,
        'da'=>-19218,'dai'=>-19212,'dan'=>-19038,'dang'=>-19023,'dao'=>-19018,'de'=>-19006,'deng'=>-19003,'di'=>-18996,'dian'=>-18977,'diao'=>-18961,'die'=>-18952,'ding'=>-18783,'diu'=>-18774,'dong'=>-18773,'dou'=>-18763,'du'=>-18756,'duan'=>-18741,'dui'=>-18735,'dun'=>-18731,'duo'=>-18722,
        'e'=>-18710,'en'=>-18697,'er'=>-18696,
        'fa'=>-18526,'fan'=>-18518,'fang'=>-18501,'fei'=>-18490,'fen'=>-18478,'feng'=>-18463,'fo'=>-18448,'fou'=>-18447,'fu'=>-18446,
        'ga'=>-18239,'gai'=>-18237,'gan'=>-18231,'gang'=>-18220,'gao'=>-18211,'ge'=>-18201,'gei'=>-18184,'gen'=>-18183,'geng'=>-18181,'gong'=>-18012,'gou'=>-17997,'gu'=>-17988,'gua'=>-17970,'guai'=>-17964,'guan'=>-17961,'guang'=>-17950,'gui'=>-17947,'gun'=>-17931,'guo'=>-17928,
        'ha'=>-17922,'hai'=>-17759,'han'=>-17752,'hang'=>-17733,'hao'=>-17730,'he'=>-17721,'hei'=>-17703,'hen'=>-17701,'heng'=>-17697,'hong'=>-17692,'hou'=>-17683,'hu'=>-17676,'hua'=>-17496,'huai'=>-17487,'huan'=>-17482,'huang'=>-17468,'hui'=>-17454,'hun'=>-17433,'huo'=>-17427,
        'ji'=>-17417,'jia'=>-17202,'jian'=>-17185,'jiang'=>-16983,'jiao'=>-16970,'jie'=>-16942,'jin'=>-16915,'jing'=>-16733,'jiong'=>-16708,'jiu'=>-16706,'ju'=>-16689,'juan'=>-16664,'jue'=>-16657,'jun'=>-16647,
        'ka'=>-16474,'kai'=>-16470,'kan'=>-16465,'kang'=>-16459,'kao'=>-16452,'ke'=>-16448,'ken'=>-16433,'keng'=>-16429,'kong'=>-16427,'kou'=>-16423,'ku'=>-16419,'kua'=>-16412,'kuai'=>-16407,'kuan'=>-16403,'kuang'=>-16401,'kui'=>-16393,'kun'=>-16220,'kuo'=>-16216,
        'la'=>-16212,'lai'=>-16205,'lan'=>-16202,'lang'=>-16187,'lao'=>-16180,'le'=>-16171,'lei'=>-16169,'leng'=>-16158,'li'=>-16155,'lia'=>-15959,'lian'=>-15958,'liang'=>-15944,'liao'=>-15933,'lie'=>-15920,'lin'=>-15915,'ling'=>-15903,'liu'=>-15889,'long'=>-15878,'lou'=>-15707,'lu'=>-15701,'lv'=>-15681,'luan'=>-15667,'lue'=>-15661,'lun'=>-15659,'luo'=>-15652,
        'ma'=>-15640,'mai'=>-15631,'man'=>-15625,'mang'=>-15454,'mao'=>-15448,'me'=>-15436,'mei'=>-15435,'men'=>-15419,'meng'=>-15416,'mi'=>-15408,'mian'=>-15394,'miao'=>-15385,'mie'=>-15377,'min'=>-15375,'ming'=>-15369,'miu'=>-15363,'mo'=>-15362,'mou'=>-15183,'mu'=>-15180,
        'na'=>-15165,'nai'=>-15158,'nan'=>-15153,'nang'=>-15150,'nao'=>-15149,'ne'=>-15144,'nei'=>-15143,'nen'=>-15141,'neng'=>-15140,'ni'=>-15139,'nian'=>-15128,'niang'=>-15121,'niao'=>-15119,'nie'=>-15117,'nin'=>-15110,'ning'=>-15109,'niu'=>-14941,'nong'=>-14937,'nu'=>-14933,'nv'=>-14930,'nuan'=>-14929,'nue'=>-14928,'nuo'=>-14926,
        'o'=>-14922,'ou'=>-14921,
        'pa'=>-14914,'pai'=>-14908,'pan'=>-14902,'pang'=>-14894,'pao'=>-14889,'pei'=>-14882,'pen'=>-14873,'peng'=>-14871,'pi'=>-14857,'pian'=>-14678,'piao'=>-14674,'pie'=>-14670,'pin'=>-14668,'ping'=>-14663,'po'=>-14654,'pu'=>-14645,
        'qi'=>-14630,'qia'=>-14594,'qian'=>-14429,'qiang'=>-14407,'qiao'=>-14399,'qie'=>-14384,'qin'=>-14379,'qing'=>-14368,'qiong'=>-14355,'qiu'=>-14353,'qu'=>-14345,'quan'=>-14170,'que'=>-14159,'qun'=>-14151,
        'ran'=>-14149,'rang'=>-14145,'rao'=>-14140,'re'=>-14137,'ren'=>-14135,'reng'=>-14125,'ri'=>-14123,'rong'=>-14122,'rou'=>-14112,'ru'=>-14109,'ruan'=>-14099,'rui'=>-14097,'run'=>-14094,'ruo'=>-14092,
        'sa'=>-14090,'sai'=>-14087,'san'=>-14083,'sang'=>-13917,'sao'=>-13914,'se'=>-13910,'sen'=>-13907,'seng'=>-13906,'sha'=>-13905,'shai'=>-13896,'shan'=>-13894,'shang'=>-13878,'shao'=>-13870,'she'=>-13859,'shen'=>-13847,'sheng'=>-13831,'shi'=>-13658,'shou'=>-13611,'shu'=>-13601,'shua'=>-13406,'shuai'=>-13404,'shuan'=>-13400,'shuang'=>-13398,'shui'=>-13395,'shun'=>-13391,'shuo'=>-13387,'si'=>-13383,'song'=>-13367,'sou'=>-13359,'su'=>-13356,'suan'=>-13343,'sui'=>-13340,'sun'=>-13329,'suo'=>-13326,
        'ta'=>-13318,'tai'=>-13147,'tan'=>-13138,'tang'=>-13120,'tao'=>-13107,'te'=>-13096,'teng'=>-13095,'ti'=>-13091,'tian'=>-13076,'tiao'=>-13068,'tie'=>-13063,'ting'=>-13060,'tong'=>-12888,'tou'=>-12875,'tu'=>-12871,'tuan'=>-12860,'tui'=>-12858,'tun'=>-12852,'tuo'=>-12849,
        'wa'=>-12838,'wai'=>-12831,'wan'=>-12829,'wang'=>-12812,'wei'=>-12802,'wen'=>-12607,'weng'=>-12597,'wo'=>-12594,'wu'=>-12585,
        'xi'=>-12556,'xia'=>-12359,'xian'=>-12346,'xiang'=>-12320,'xiao'=>-12300,'xie'=>-12120,'xin'=>-12099,'xing'=>-12089,'xiong'=>-12074,'xiu'=>-12067,'xu'=>-12058,'xuan'=>-12039,'xue'=>-11867,'xun'=>-11861,
        'ya'=>-11847,'yan'=>-11831,'yang'=>-11798,'yao'=>-11781,'ye'=>-11604,'yi'=>-11589,'yin'=>-11536,'ying'=>-11358,'yo'=>-11340,'yong'=>-11339,'you'=>-11324,'yu'=>-11303,'yuan'=>-11097,'yue'=>-11077,'yun'=>-11067,
        'za'=>-11055,'zai'=>-11052,'zan'=>-11045,'zang'=>-11041,'zao'=>-11038,'ze'=>-11024,'zei'=>-11020,'zen'=>-11019,'zeng'=>-11018,'zha'=>-11014,'zhai'=>-10838,'zhan'=>-10832,'zhang'=>-10815,'zhao'=>-10800,'zhe'=>-10790,'zhen'=>-10780,'zheng'=>-10764,'zhi'=>-10587,'zhong'=>-10544,'zhou'=>-10533,'zhu'=>-10519,'zhua'=>-10331,'zhuai'=>-10329,'zhuan'=>-10328,'zhuang'=>-10322,'zhui'=>-10315,'zhun'=>-10309,'zhuo'=>-10307,'zi'=>-10296,'zong'=>-10281,'zou'=>-10274,'zu'=>-10270,'zuan'=>-10262,'zui'=>-10260,'zun'=>-10256,'zuo'=>-10254
    );

    /**
     * 将中文编码成拼音
     * @param string $utf8Data utf8字符集数据
     * @param string $sRetFormat 返回格式 [head:首字母|all:全拼音]
     * @return string
     */
    public static function encode($utf8Data, $sRetFormat='head'){
        $sGBK = iconv('UTF-8', 'GBK', $utf8Data);
        $aBuf = array();
        for ($i=0, $iLoop=strlen($sGBK); $i<$iLoop; $i++) {
            $iChr = ord($sGBK{$i});
            if ($iChr>160)
                $iChr = ($iChr<<8) + ord($sGBK{++$i}) - 65536;
            if ('head' === $sRetFormat)
                $aBuf[] = substr(self::zh2py($iChr),0,1);
            else
                $aBuf[] = self::zh2py($iChr);
        }
        if ('head' === $sRetFormat)
            return implode('', $aBuf);
        else
            return implode('', $aBuf);
    }

    /**
     * 中文转换到拼音(每次处理一个字符)
     * @param number $iWORD 待处理字符双字节
     * @return string 拼音
     */
    private static function zh2py($iWORD) {
        if($iWORD>0 && $iWORD<160 ) {
            return chr($iWORD);
        } elseif ($iWORD<-20319||$iWORD>-10247) {
            return '';
        } else {
            foreach (self::$_aMaps as $py => $code) {
                if($code > $iWORD) break;
                $result = $py;
            }
            return $result;
        }
    }
}